package pl.mchaniewski.ryneczek.web.user;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.Portfolio;
import pl.mchaniewski.ryneczek.pojo.User;
import pl.mchaniewski.ryneczek.services.PortfolioService;
import pl.mchaniewski.ryneczek.services.UserService;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.utilities.SecurityUtil;
import pl.mchaniewski.ryneczek.web.FormButton;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class NewPortfolioBean extends FormButton {
    private PortfolioService portfolioService;
    private UserService userService;
    private PortfolioListBean portfolioListBean;

    /* Form */
    @Size(min = 1, max = 20, message = "{newportfoliobean.namesize}")
    private String name;
    @DecimalMin(value = "10", message = "{newportfoliobean.balancemin}")
    @DecimalMax(value = "10000", message = "{newportfoliobean.balancemax}")
    private BigDecimal balance;

    /* PostConstruct parameters */
    private Integer howManyCanCreate;

    @Autowired
    public void setPortfolioService(PortfolioService portfolioService) {
        this.portfolioService = portfolioService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setPortfolioListBean(PortfolioListBean portfolioListBean) {
        this.portfolioListBean = portfolioListBean;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public Integer getHowManyCanCreate() {
        return howManyCanCreate;
    }

    @PostConstruct
    public void init() {
        String loggedUsername = SecurityUtil.getUserDetails().getUsername();
        Integer portfolioNumber = portfolioService.findByUsername(
                loggedUsername).size();
        howManyCanCreate = Portfolio.MAXIMUM_PORTFOLIOS - portfolioNumber;

        if (howManyCanCreate.equals(0)) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_INDEX);
        }
    }

    public String create() {
        User user = userService.findByLogin(SecurityUtil.getUserDetails()
                .getUsername());
        if (user == null) {
            return NavigationUtil.facesRedirectTo(NavigationUtil.INDEX);
        } else {
            List<Portfolio> list = portfolioService.findByUserId(user
                    .getUserid());

            int currentPortfolioCount = (list != null) ? list.size() : 0;

            if (currentPortfolioCount >= Portfolio.MAXIMUM_PORTFOLIOS) {
                FacesMessageUtil
                        .addMessage(
                                getButton(),
                                I18nUtil.getLocalizedMessage("newportfoliobean.cantCreateMore"),
                                FacesMessage.SEVERITY_WARN);

                return NavigationUtil.SAME_PAGE;
            }

            if (portfolioService.createNewPortfolio(user, getName(),
                    getBalance()) != null) {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("newportfoliobean.created"),
                        FacesMessage.SEVERITY_INFO);

                --howManyCanCreate;

                portfolioListBean.init();
            } else {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("newportfoliobean.notCreated"),
                        FacesMessage.SEVERITY_WARN);
            }

            return NavigationUtil.SAME_PAGE;
        }
    }

}
